import {Inject} from 'plugins'
import config from 'config';

@Inject('$scope', '$state', 'ui.dialog', 'ui.http', 'ui.api', 'OrgService', 'DepartService')
export class DepartUserList {
	constructor($scope, $state, dialog, http, api, appService, service) {
		var appScope = $scope.$parent.$parent;

		function getTreeNode() {
			return appScope.getTreeNode();
		}

		appScope.changeState();

		var q = $scope.q = {};

		var loadData = $scope.loadData = function(params) {
			var node = getTreeNode();
			if (!node) return;
			params = params || {};
			angular.extend(params, {
				id: node.id
			})
			api.gridLoad({
				name: 'org_branch_userList',
				params: params,
				scope: $scope,
				success: function(data, options) {
					var _scope = this;
					_scope.fields = data.fields;
				}
			});
		};

		var query = $scope.query = function(resetPage) {
			if (resetPage === false || $scope.gridOptions.paginationCurrentPage == 1) {
				loadData(q);
			} else {
				api.gridReset(null, $scope);
			}
		}

		$scope.addDepart = function() {
			service.add(appScope);
		}

		$scope.add = function() {
			var node = getTreeNode();
			api.form({
				title: '新建用户',
				template: require('../../user/views/form.tpl.html'),
				name: 'org_user_add',
				data: {
					/*id: node.id*/
				},
				beforeSettings: function() {
					var _scope = this;
					api.tree({
						scope: _scope,
						type: 'checkbox',
						url: 'basic/branch/selectedBranchTree',
						params: {nodeId:node.id},
						paths: []
					});
				},
				scope: {
					moveAdd: appService.moveAdd,
					moveRemove: appService.moveRemove
				},
				resolveWait: {
					roles: function() {
						return http.post('org_full_roles');
					}
				},
				resolveApplyScope: ['roles'],
				beforeSubmit: function(data) {
					var _scope = this;
					data.roleIds = (data.roles || []).map(function(role) {
						return role.id;
					});
					data.roles = null;
					delete data.roles;

					data.branchIds = api.getTreeChecked(_scope.tree).map(function(node) {
						return node.id;
					});

					if($.inArray(node.id, data.branchIds) <0) {
	                    data.branchIds.push(node.id);
					}
				}
			}).then(function() {
				query();
			});
		}
		$scope.edit = function() {
			var node = getTreeNode();
			var id = api.getGridSelectedIds($scope);
			var useId = id[0];
			api.form({
				title: '修改用户',
				template: require('../../user/views/form.tpl.html'),
				name: 'org_user_edit',
				data: {
					id: id
				},
				beforeSettings: function() {
					var _scope = this;
					api.tree({
						scope: _scope,
						type: 'checkbox',
						url: 'basic/branch/selectedBranchTree',
						params: {
							useId: useId
						},
						paths: []
					});
				},
				scope: {
					moveAdd: appService.moveAdd,
					moveRemove: appService.moveRemove
				},
				resolveWait: {
					roles: function() {
						return http.post({
							name: 'org_remaining_roles',
							params: {
								id: id
							}
						});
					},
					item: function() {
						return http.post({
							name: 'org_user',
							params: {
								id: api.getGridSelectedId($scope)
							}
						})
					}
				},
				resolveApplyScope: ['roles'],
				resolveApplyData: ['item'],
				beforeSubmit: function(data) {
					var _scope = this;
					data.roleIds = (data.roles || []).map(function(role) {
						return role.id;
					});
					data.roles = null;
					delete data.roles;

					data.branchIds = api.getTreeChecked(_scope.tree).map(function(node) {
						return node.id;
					});
				}
			}).then(function() {
				query(false);
			});
		}
		$scope.remove = function() {
			var node = getTreeNode();
			var id = node.id;
			var ids = api.getGridSelectedIds($scope);
			dialog.confirm('确定要移除已选择的用户？').result.then(function(r) {
				if (r) {
					http.post({
						name: 'org_depart_userAddAndRemove',
						params: {
							id: id,
							ids: ids,
							type: 2,
						},
						success: function() {
							query(false);
						}
					})
				}
			});
		}

		$scope.import = function() {
			var node = getTreeNode();
			var id = node.id;

			var loadList = function(scope, params) {
				scope = scope || this;
				params = params || {};
				angular.extend(params, {
					id: id
				});
				return api.gridLoad({
					name: 'org_depart_remaining_users',
					params: params,
					scope: scope,
					success: function(data, options) {
						var _scope = this;
						_scope.fields = data.fields;
					}
				});
			};
			api.form({
				title: '添加用户',
				template: require('../views/form_import.tpl.html'),
				scope: {
					q: {},
					gridOptions: {
						paginationCurrentPage: api.page.pageNumber,
						paginationPageSize: api.page.pageSize,
						useExternalPagination: true,
						columns: [{
							name: '序号',
							width: 50,
							cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
						}, {
							name: '用户名',
							align: 'left',
							width: 150,
							field: 'username'
						}, {
							name: '真实姓名',
							width: 150,
							field: 'realname'
						}, {
							name: '当前状态',
							width: 100,
							field: 'status',
							cellTemplate: '<div class="x-grid-inner" ng-bind-html="grid.appScope.mapping(grid, row, col, \'status\')"></div>'

						}, {
							name: '创建时间',
							width: 200,
							field: 'crtime'
						}],
						data: [],
						onRegisterApi: function(api, grid) {
							var _scope = grid.appScope;
							_scope.api = api;

							api.pagination && api.pagination.on.paginationChanged(_scope, function(newPage, pageSize) {
								_scope.query(false);
							});
						}
					},
					mapping: function(grid, row, col, field) {
						return api.mapping({
							grid: grid,
							row: row,
							col: col,
							field: field,
							scope: this
						});
					},
					query: function(resetPage) {
						var _scope = this;
						if (resetPage === false || _scope.gridOptions.paginationCurrentPage == 1) {
							loadList(_scope, _scope.q);
						} else {
							api.gridReset(null, _scope);
						}
					}
				},
				name: 'org_depart_userAddAndRemove',
				data: {
					id: id
				},
				beforeSubmit: function(data, defered) {
					var ids = api.getGridSelectedIds(this);
					if (ids.length === 0) {
						dialog.alert('请选择需要添加的用户！');
						return false;
					}
					data.ids = ids;
					data.type = 1;
				},
				resolveApply: false,
				resolveWait: function() {
					var _scope = this;
					return loadList(_scope);
				},
				config: {
					size: 680
				}
			}).then(function() {
				query();
			});
		}

		$scope.gridOptions = {
			paginationCurrentPage: api.page.pageNumber,
			paginationPageSize: api.page.pageSize,
			useExternalPagination: true,
			columns: [{
				name: '序号',
				width: 50,
				cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
			}, {
				name: '用户名',
				align: 'left',
				width: 150,
				field: 'username'
			}, {
				name: '真实姓名',
				width: 150,
				field: 'realname'
			}, {
				name: '当前状态',
				width: 100,
				field: 'status',
				cellTemplate: '<div class="x-grid-inner" ng-bind-html="grid.appScope.mapping(grid, row, col, \'status\')"></div>'

			}, {
				name: '创建时间',
				width: 200,
				field: 'crtime'
			}],
			forceFit: false,
			onRegisterApi: function(api) {
				$scope.api = api;
				api.pagination && api.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
					query(false);
				});
			}
		};

		$scope.mapping = function(grid, row, col, field) {
			return api.mapping({
				grid: grid,
				row: row,
				col: col,
				field: field,
				scope: $scope
			});
		}

	    $scope.hasSelected = function() {
	        return api.hasGridSelected($scope) && api.getGridSelectedRecord($scope).status != -1;
	    }
	    $scope.hasSelectedRecords = function() {
	        return api.hasGridSelectedRecords($scope) && api.getGridSelectedRecords($scope).filter(function(r) {
	                return r.status == -1;
	            }).length == 0;
	    }

		query();
	}
}